package com.appspot.zcmjqm.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.appspot.zcmjqm.app.model.Product;
import com.appspot.zcmjqm.app.model.category.ProductCategory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@Service
public class ProductServiceJPAImpl implements ProductService {
	
	@Autowired
	private EntityManager entityManager;
	
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@Transactional
	public List<ProductCategory> getAllCategories() {
		List<?> l = entityManager.createQuery("select from ProductCategory").getResultList();
		List<ProductCategory> categories = new ArrayList<ProductCategory>();
		for (Object o : l) {
			categories.add((ProductCategory) o);
		}
		return categories;
	}

	@Transactional
	public List<Product> getByCategory(String categoryKey) {
		ProductCategory productCategory = new ProductCategory();
		Key k = KeyFactory.stringToKey(categoryKey);
		productCategory.setKey(k);
		Query query = entityManager.createQuery("select from Product where productCategory = :cat");
		query.setParameter("cat", productCategory);
		List<?> l = query.getResultList();
		List<Product> products = new ArrayList<Product>();
		for (Object o : l) {
			products.add((Product) o);
		}
		return products;
	}

	@Transactional
	public Product getById(String key) {
		Key k = KeyFactory.stringToKey(key);
		return entityManager.find(Product.class, KeyFactory.keyToString(k));
	}

}